package com.kaesar.thread.ShiZhanJavaGaoBingFaSheJi2.chp3;

import java.util.concurrent.*;

/**
 * 线程池使用示例
 *
 * @Author: chengk
 * @Date: 2021/7/31 9:22 上午
 */
public class DivTask implements Runnable {
    int a, b;

    public DivTask(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public void run() {
        double re = a / b;
        System.out.println(re);
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadPoolExecutor pools = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());

        // 这种方式只能得到4个输出，也不会打错误日志。除数为0的没有输出，也没有报错，是个坑
        for (int i = 0; i < 5; i++) {
            pools.submit(new DivTask(100, i));
        }

        Thread.sleep(2000);
        System.out.println();

        // 这种方式会得到4个输出，而且会抛异常： Exception in thread "pool-1-thread-6" java.lang.ArithmeticException: / by zero
        // 所以 execute() 方法 比 submit() 合适
        for (int i = 0; i < 5; i++) {
            pools.execute(new DivTask(100, i));
        }

        Thread.sleep(2000);
        System.out.println();

        // 这种方式也会把错误跑出来
        for (int i = 0; i < 5; i++) {
            Future re = pools.submit(new DivTask(100, i));
            re.get();
        }
    }
}
